package com.un.ebs.order.aspect;

import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.customer.domain.Customer;
import com.un.ebs.customer.service.CustomerService;
import com.un.ebs.order.OrderConfigureCode;
import com.un.ebs.order.domain.OrderItemExt;
import com.un.ebs.order.dto.OrderDiscountApplyAuditDto;
import com.un.ebs.order.dto.OrderDiscountApplyDto;
import com.un.ebs.order.dto.OrderExpireApplyDto;
import com.un.ebs.order.dto.OrderVo;
import com.un.ebs.order.service.OrderService;
import com.un.ebs.sys.service.ConfigureService;
import com.un.ebs.sys.service.WxService;
import com.un.ebs.workOrder.domain.WorkOrderExt;
import com.un.ebs.workOrder.service.WorkOrderService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/2/27 21:08
 */
@Aspect
@Component
public class OrderNotifyAspect {

    @Autowired
    private ConfigureService configureService;

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxService wxService;

    @Autowired
    private CustomerService customerService;

    @After("execution(* com.un.ebs.order.service.impl.OrderServiceImpl.accept(String))")
    public void acceptNotify(JoinPoint joinPoint) {
        String id = configureService.getValueByCode(OrderConfigureCode.order_accept_notify_templete_id);
        String config = configureService.getValueByCode(OrderConfigureCode.order_accept_notify_templete_config);
        OrderVo order = orderService.queryById(joinPoint.getArgs()[0].toString());
        String url = StringUtils.valueReplace(configureService.getValueByCode(OrderConfigureCode.order_accept_notify_templete_url), "\\{", "\\}", SecurityUtils.getUserContent());

        if (!(StringUtils.isNullOrEmpty(config) || StringUtils.isNullOrEmpty(id))) {
            Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);
            System.out.println("URL : " + url);
            Customer customer = customerService.queryById(order.getCustId());

            if (customer == null) {
                return;
            }
            if (StringUtils.isNullOrEmpty(customer.getUserId())) {
                return;
            }

            wxService.sendTemplateMessage(order.getTenantId(), "订单受理通知", customer.getUserId(), id, data, url);

        }
    }

    @After("execution(* com.un.ebs.order.service.impl.OrderServiceImpl.submitCancel(String,String))")
    public void cancelNotify(JoinPoint joinPoint) {
        OrderVo order = orderService.queryById(joinPoint.getArgs()[0].toString());
        String id = configureService.getValueByCode(OrderConfigureCode.order_cancel_notify_templete_id, order.getTenantId());
        String config = configureService.getValueByCode(OrderConfigureCode.order_cancel_notify_templete_config, order.getTenantId());
        if (StringUtils.isNullOrEmpty(id) || StringUtils.isNullOrEmpty(config)) {
            return;
        }

        String url = StringUtils.valueReplace(configureService.getValueByCode(OrderConfigureCode.order_cancel_notify_templete_url), "\\{", "\\}", SecurityUtils.getUserContent());
        Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);

        wxService.sendTemplateMessage(order.getTenantId(), "订单取消通知", order.getCreateAt(), id, data, url);
    }

    @After("execution(* com.un.ebs.order.service.impl.OrderServiceImpl.discountApply(com.un.ebs.order.dto.OrderDiscountApplyDto))")
    public void discountApplyNotify(JoinPoint joinPoint) {
        OrderVo order = orderService.queryById(((OrderDiscountApplyDto) joinPoint.getArgs()[0]).getOrderId());
        String id = configureService.getValueByCode(OrderConfigureCode.order_discount_apply_notify_templete_id, SecurityUtils.getTenantId());
        String config = configureService.getValueByCode(OrderConfigureCode.order_discount_apply_notify_templete_config, SecurityUtils.getTenantId());

        String url = String.format("http://www.cloud-client.cn/ebs/wechat/index.html?tenantId=%s#/mgrOrderItem/%s", SecurityUtils.getTenantId(), order.getId());

        if (StringUtils.isNullOrEmpty(id) || StringUtils.isNullOrEmpty(config)) {
            return;
        }

        Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);
        wxService.sendTemplateMessage(order.getTenantId(), "订单优惠申请", order.getDiscountAuditUserId(), id, data, url);
    }

    @After("execution(* com.un.ebs.order.service.impl.OrderServiceImpl.discountApplyAudit(com.un.ebs.order.dto.OrderDiscountApplyAuditDto))")
    public void discountApplyAuditNotify(JoinPoint joinPoint) {
        OrderDiscountApplyAuditDto audit = ((OrderDiscountApplyAuditDto) joinPoint.getArgs()[0]);
        OrderVo order = orderService.queryById(audit.getOrderId());
        String id = configureService.getValueByCode(OrderConfigureCode.order_discount_apply_notify_templete_id, SecurityUtils.getTenantId());
        String config = configureService.getValueByCode(OrderConfigureCode.order_discount_apply_notify_templete_config, SecurityUtils.getTenantId());

        String url = String.format("http://www.cloud-client.cn/ebs/wechat/index.html?tenantId=%s#/mgrOrderItem/%s", SecurityUtils.getTenantId(), order.getId());

        if (StringUtils.isNullOrEmpty(id) || StringUtils.isNullOrEmpty(config)) {
            return;
        }

        String title;
        if (audit.getIsPass()) {
            Double discountMoney = audit.getItems().stream().mapToDouble(s -> s.getDiscountMoney()).sum();
            title = String.format("优惠申请已通过：%s", discountMoney == null ? 0 : discountMoney);
        } else {
            title = "优惠申请不通过，原因：" + audit.getRemark();
        }

        Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);
        wxService.sendTemplateMessage(order.getTenantId(), title, order.getSubmitUserId(), id, data, url);
    }

    @After("execution(* com.un.ebs.order.service.impl.OrderServiceImpl.expireApply(com.un.ebs.order.dto.OrderExpireApplyDto))")
    public void expireApplyNotify(JoinPoint joinPoint) {
        OrderVo order = orderService.queryById(((OrderExpireApplyDto) joinPoint.getArgs()[0]).getOrderId());
        String id = configureService.getValueByCode(OrderConfigureCode.order_expire_apply_notify_templete_id, SecurityUtils.getTenantId());
        String config = configureService.getValueByCode(OrderConfigureCode.order_expire_apply_notify_templete_config, SecurityUtils.getTenantId());

        String url = String.format("http://www.cloud-client.cn/ebs/wechat/index.html?tenantId=%s#/mgrOrderItem/%s", SecurityUtils.getTenantId(), order.getId());

        if (StringUtils.isNullOrEmpty(id) || StringUtils.isNullOrEmpty(config)) {
            return;
        }

        Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);
        wxService.sendTemplateMessage(order.getTenantId(), "订单优惠申请", order.getPaymentExpireApplyAuditUserId(), id, data, url);
    }

    @After(value = "execution(* com.un.ebs.workOrder.service.impl.WorkOrderServiceImpl.complete(String,String,Double,Double,java.util.List<org.springframework.web.multipart.MultipartFile>))")
    public void completeNotify(JoinPoint joinPoint) {
        completeNotify(joinPoint.getArgs()[0].toString());
    }

    @After(value = "execution(* com.un.ebs.workOrder.service.impl.WorkOrderServiceImpl.audit(String,Boolean,String))")
    public void completeAuditNotify(JoinPoint joinPoint) {
        completeNotify(joinPoint.getArgs()[0].toString());
    }

    private void completeNotify(String workOrderId) {
        WorkOrderExt wo = workOrderService.queryById(workOrderId);
        if (wo == null) {
            throw new BusinessException("工单没有找到。");
        }
        OrderVo order = orderService.queryById(wo.getOrderId());
        for (OrderItemExt item : order.getItems()) {
            if (!item.getDeliverStatus()) {
                return;
            }
        }

        String id = configureService.getValueByCode(OrderConfigureCode.order_complete_notify_templete_id);
        String config = configureService.getValueByCode(OrderConfigureCode.order_complete_notify_templete_config);
        String url = StringUtils.valueReplace(configureService.getValueByCode(OrderConfigureCode.order_complete_notify_templete_url), "\\{", "\\}", SecurityUtils.getUserContent());

        if (StringUtils.isNullOrEmpty(config) || StringUtils.isNullOrEmpty(id)) {
            return;
        }
        Map<String, String> data = StringUtils.splitTemplate(config.split("~"), order);

        wxService.sendTemplateMessage(order.getTenantId(), "订单完成通知", order.getCreateAt(), id, data, url);
    }

}
